package com.baidu.translate.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.translate.demo.TransApi;

public class BaiduTranslateUtil {

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "20170511000047023";
    private static final String SECURITY_KEY = "_8G2iyI9RXv7BQZBBxKi";

    public static JSONArray baiduTranslate(String language,String content) {
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        System.out.println(content+"-----");
        String retStr=api.getTransResult(content, "zh", language);
        JSONObject retJson=JSON.parseObject(retStr);
		JSONArray retResult=retJson.getJSONArray("trans_result");
		if (retResult.size() > 1) {
			String dst = "";
			String src = "";
			for (int i = 0; i < retResult.size(); i++) {
				dst += retResult.getJSONObject(i).getString("dst")+"\\n";
				src += retResult.getJSONObject(i).getString("src")+"\\n";
			}
			String retContent = "[{\"src\":\""+src+"\",\"dst\":\""+dst+"\"}]";
			retResult = JSONArray.parseArray(retContent);
			System.out.println(retContent);
		}
		System.out.println(retResult);
		/*retResult = JSONArray.parseArray(retContent);*/
		return retResult;
    }

}
